/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.web.front;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.boxin.ims.modules.wechat.entity.LotteryRecord;
import com.boxin.ims.modules.wechat.entity.Product;
import com.boxin.ims.modules.wechat.entity.UserDefine;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.score.entity.ExchangeRecord;
import com.boxin.ims.modules.wechat.score.entity.ScoreExchange;
import com.boxin.ims.modules.wechat.score.service.ExchangeRecordService;
import com.boxin.ims.modules.wechat.score.service.ScoreExchangeService;
import com.boxin.ims.modules.wechat.service.LotteryConfigService;
import com.boxin.ims.modules.wechat.service.LotteryRecordService;
import com.boxin.ims.modules.wechat.service.LotteryService;
import com.boxin.ims.modules.wechat.service.ProductService;
import com.boxin.ims.modules.wechat.service.SeckillService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.utils.ScoreUtils;
import com.boxin.ims.modules.wechat.utils.WechatUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 产品Controller
 * @author Jakemanse
 * @version 2013-06-28
 */
@Controller
@RequestMapping(value = Global.FRONT_PATH+"/wechat")
public class WechatFrontController extends BaseController {

	@Autowired
	private ProductService productService;
	
	
	@Autowired
	private LotteryRecordService lotteryRecordService;
	
	@Autowired
	LotteryConfigService lotteryConfigService;
	
	@Autowired
	private WechatMemberService wechatMemberService;
	
	@Autowired
	private WechatDaoHelper wechatDaoHelper;
	
	
	@Autowired
	private ScoreExchangeService scoreExchangeService;
	
	@Autowired
	private ExchangeRecordService exchangeRecordService;
	
	@Autowired
	SystemService systemService;
	
	
	private static Map<String,String> topageMap = new HashMap<String,String>();
	
	
	@ModelAttribute
	public Product get(@RequestParam(required=false) Long id) {
		if (id != null){
			return productService.get(id);
		}else{
			return new Product();
		}
	}

	
	
	@RequestMapping(value = "mobiles")
	public String initWehcatLotteryMobiles(  HttpServletRequest request, HttpServletResponse response, Model model,RedirectAttributes redirectAttributes) {
		String day = DateUtils.getTodayString();
		Map<String, String> params = new HashMap<String,String>();
		params.put("day", day);
		params.put("userId", ""+UserUtils.getUser().getId());
		List<Map<String,Object>> result = 	wechatDaoHelper.queryNewMembers(params);
		responseJson(request, response, result);
		return null;
	}
	
	
	
	
	
	
	
	@RequestMapping(value = {"list", ""})
	public String list(Product product, HttpServletRequest request, HttpServletResponse response, Model model) {
//		User user = UserUtils.getUser();
//		if (!user.isAdmin()){
//			product.setUser(user);
//		}
		String category  = request.getParameter("category");
		String subCategory = request.getParameter("subCategory");
		if(StringUtils.isNotEmpty(category)  && !"0".equals(category)) {
			product.setCategory(Integer.parseInt(category));
		}
		
		if(StringUtils.isNotEmpty(subCategory) && !"0".equals(subCategory)){
			product.setSubCategory(Integer.parseInt(subCategory));
		}
		
        Page<Product> page = productService.find(new Page<Product>(request, response), product); 
        model.addAttribute("page", page);
        model.addAttribute("category", category);
        model.addAttribute("subCategory", subCategory);
        model.addAttribute("pagination", page.simplePagination());
		return "modules/wechat/front/productList";
	}
	
	
	
	
	@RequestMapping(value = {"detail/{id}"+Global.URL_SUFFIX})
	public String detail(@PathVariable("id") Long id,Model model, HttpServletRequest request, HttpServletResponse response ) {
//		User user = UserUtils.getUser();
//		if (!user.isAdmin()){
//			product.setUser(user);
//		}
		Product product = productService.get(id);
		model.addAttribute("product", product);
		
		return "modules/wechat/front/productDetail";
	}
	
	
	@RequestMapping(value = "logout/{id}")
	public String logout(@PathVariable("id") Long id,Model model, HttpServletRequest request, HttpServletResponse response ) {
		
		request.getSession(true).setAttribute("wechatUser"+id, null);
		request.getSession(true).setAttribute("uid", null);
		
		return "modules/wechat/front/wechatLogin";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-29  上午10:27:31
	 * @function <p> 微信会员登录 （只用手机号即可）  </p>
	 * @param id
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	
	@RequestMapping(value = "login/{id}")
	public String login(@PathVariable("id") Long id,Model model, HttpServletRequest request, HttpServletResponse response ) {
//		}
		
		User user = new User();
		user.setId(id);
		String message = "";
		
		String mobile = request.getParameter("mobile");
		String wechatId =  request.getParameter("wechatId");
		String topage = request.getParameter("topage");
		String loginFlag = request.getParameter("login");
		
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("topage", topage);
		model.addAttribute("reg", "reg");
		model.addAttribute("id", id);
		model.addAttribute("uid", id);
		
		if(StringUtils.isEmpty(mobile)  ){	//手机号为空
			if("1".equals(loginFlag)){
				message = "手机号不能为空。";
				model.addAttribute("message", message);
			}
			return "modules/wechat/front/wechatLogin";
		}
//		else if(StringUtils.isEmpty(wechatId)){	//微信号为空
//			message = "未能找到您的信息帐号信息，请在微信中回复'会员绑定' 成为我们的会员后再登录,谢谢！";
//			model.addAttribute("message", message);
//			return "modules/wechat/front/wechatLogin";
//		}
		else{
			WechatMember wechatMember = wechatMemberService.getByMobile(user, mobile);
			if(wechatMember == null){	//登录失败
				message = "登录失败，请确认您输入的手机是否正确或是否已经是我们的会员，如果不是请先请在微信中回复'会员绑定'成为我们的会员，谢谢!。";
				return "modules/wechat/front/wechatLogin";
			}else{//登录成功
				
				request.getSession(true).setAttribute("wechatUser"+id, wechatMember);
				request.getSession(true).setAttribute("uid", id);
				String tourl = getTopage(topage);
				if(!StringUtils.isEmpty(tourl)  ){
//					tourl += "?wechatId="+wechatId;
					if(tourl.contains("redirect:")  && topage.equals("exchangeScore")){
						tourl += "/"+id;
					}
					return tourl;
				}
				
				message = "<h4>登录成功！</h4><br>您现在可以参与:<br>签到送积分<br>积分兑换<br><a href=\"http://www.hdzhx.com/zxims/f/wechat/product/seckills?uid="+user.getId() +"&wechatId="+wechatId+"&topage=seckill\">在线秒杀</a><br>在线抽奖<br><br>";
				model.addAttribute("message", message);
				return "modules/wechat/front/wechatIndex";
			}
		}
		
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-1-19  下午11:19:41
	 * @function <p> 商品积分页面 </p>
	 * @param id
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "toexchange/{uid}")
	public String toExchangeScore(@PathVariable("uid") Long id,Model model, HttpServletRequest request, HttpServletResponse response){
		
		String uid = request.getParameter("uid");				//userId
		String wechatId = request.getParameter("wechatId");		//OpenId
		String mobile   = request.getParameter("mobile");		//Mobile
		
		
		
		User user = new User();
		user.setId(id);
		
		//需要判断是否已经登录过
		WechatMember member = (WechatMember)	request.getSession(true).getAttribute("wechatUser"+uid);
		if(member == null  ){	//没有登录先进入登录页面
			if( "34".equals(id)){	//阳光麦康处理
				member = wechatMemberService.getByWechatMemberId(user, wechatId);
				request.getSession(true).setAttribute("wechatUser"+uid, member);
			}else{
				request.setAttribute("topage","exchangeScore");
				request.setAttribute("wechatId",wechatId);
				request.setAttribute("id",id);
				request.setAttribute("uid",id);
				//return "redirect:" + Global.FRONT_PATH+ "/wechat/login/"+id;
				return "modules/wechat/front/wechatLogin";
				
			}
		}	
		
		
		// 兑换的列表
		List<ScoreExchange> scoreExchangeList = 	scoreExchangeService.findAllByUserId(id);
		model.addAttribute("scoreExchangeList", scoreExchangeList);
		
		
		return "modules/wechat/front/exchange/exchangeScore";	
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-2-2  下午10:29:15
	 * @function <p>导航到留言的页面 </p>
	 * @param id
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "toguestbook/{uid}")
	public String toGuestbook(@PathVariable("uid") Long id,Model model, HttpServletRequest request, HttpServletResponse response){
		
		String uid = request.getParameter("uid");				//userId
		String wechatId = request.getParameter("wechatId");		//OpenId
		String mobile   = request.getParameter("mobile");		//Mobile
		
		User user = new User();
		user.setId(id);
		
		//需要判断是否已经登录过
		WechatMember member = (WechatMember)	request.getSession(true).getAttribute("wechatUser"+uid);
		if(member == null  ){	//没有登录先进入登录页面
			if( "34".equals(id)){	//阳光麦康处理
				member = wechatMemberService.getByWechatMemberId(user, wechatId);
				request.getSession(true).setAttribute("wechatUser"+uid, member);
			}else{
				request.setAttribute("topage","guestbook");
				request.setAttribute("wechatId",wechatId);
				request.setAttribute("id",id);
				request.setAttribute("uid",id);
				//return "redirect:" + Global.FRONT_PATH+ "/wechat/login/"+id;
				return "modules/wechat/front/wechatLogin";
				
			}
		}	
		
		
		// 兑换的列表
		List<ScoreExchange> scoreExchangeList = 	scoreExchangeService.findAllByUserId(id);
		model.addAttribute("scoreExchangeList", scoreExchangeList);
		
		
		return "modules/wechat/front/exchange/exchangeScore";	
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-2-5  下午9:59:55
	 * @function <p> 导航到网页签到 </p>
	 * @param uid
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "tosignup/{uid}")
	public String toSignup(@PathVariable("uid") Long uid,Model model, HttpServletRequest request, HttpServletResponse response){
		String openId = request.getParameter("oid");
		model.addAttribute("uid", uid);
		model.addAttribute("wechatId", openId);
		
		return "modules/wechat/front/toSignup";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-2-5  下午10:00:26
	 * @function <p> 签到处理  </p>
	 * @param uid
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "signup/{uid}")
	public String signup(@PathVariable("uid") Long uid,Model model, HttpServletRequest request, HttpServletResponse response){
		String wechatId = request.getParameter("wid");
		String pwd =  request.getParameter("pwd");
		User user = new User();
		user.setId(uid);
		WechatMember member =	wechatMemberService.getByWechatMemberId(user, wechatId);
		String message = "";
		if(member != null){
			
			UserDefine userDefine = WechatUtils.getUserDefineByUserId(user.getId());	//定义
			String upcon = "签到";
			
			if(DateUtils.getTodayString().equals(member.getLastSignTime())){	//未签到+签到成功
				Integer score = member.getScore();
				score = (score==null) ? 0 :score;
				message = WechatUtils.processUserBusinessReply(user.getId(), upcon, score);
				if(com.thinkgem.jeesite.common.utils.StringUtils.isEmpty(message)){
					message = "今天您已签到过了,您当前的积分为:"+score+"分!";
				}else{
					message = message.replaceAll("%分值%", userDefine.getSignScore()+"");
					message = message.replaceAll("%积分%", score+"");
					message =  "今天您已签到过了," + message;
				}
			}else{
				//已签到过
				Integer score = member.getScore();
				score = (score==null) ? 1 :score+userDefine.getSignScore();
				member.setScore(score);
				member.setUpdateTime(new Date());
				member.setLastSignTime(DateUtils.getTodayString());
				wechatMemberService.save(member);
				
				message = WechatUtils.processUserBusinessReply(user.getId(), upcon, score);
				if(com.thinkgem.jeesite.common.utils.StringUtils.isEmpty(message)){
					message = "签到成功,您当前的积分为:"+score+"分!";
				}else{
					message = message.replaceAll("%分值%", userDefine.getSignScore()+"");
					message = message.replaceAll("%积分%", score+"");
				}
				
				ScoreUtils.addWechatMemberSignScore(member,userDefine.getSignScore());
			}
			
		}else{
			//还不是会员
			message = "您还不是我们的会员请先注册会员，请签到吧！";
			model.addAttribute("message", message);
			model.addAttribute("wechatId", wechatId);
			return bind(uid, model, request, response);
			
		}
		
		model.addAttribute("message", message);
		
		return "modules/wechat/front/signupOk";
	}
	
	
	
	
	@RequestMapping(value = "doexchange/{uid}")
	public String doExchange(@PathVariable("uid") Long uid,Model model, HttpServletRequest request, HttpServletResponse response){
		String score =  request.getParameter("score");	
		String proName =  request.getParameter("proName");	
		String seller	= request.getParameter("seller");

		String wechatId = request.getParameter("wechatId");		//OpenId
 		String mobile   = request.getParameter("mobile");		//Mobile
 		String exchangeId   = request.getParameter("exchangeId");		//对应的兑换项ID
		
		
		User user = UserUtils.getUserById(uid);
		
		
		//需要判断是否已经登录过
		WechatMember member = (WechatMember)	request.getSession(true).getAttribute("wechatUser"+uid);
		if(member == null  ){	//没有登录先进入登录页面
			if( "34".equals(uid)){	//阳光麦康处理
				member = wechatMemberService.getByWechatMemberId(user, wechatId);
				request.getSession(true).setAttribute("wechatUser"+wechatId, member);
			}else{
				
				
				request.setAttribute("topage","exchangeScore");
				request.setAttribute("wechatId",wechatId);
				request.setAttribute("id",uid);
				request.setAttribute("uid",uid);
				//return "redirect:" + Global.FRONT_PATH+ "/wechat/login/"+id;
//				Integer scoreM = Integer.parseInt(score);
//				ScoreUtils.addWechatExchangeScore(member, scoreM,"");
				
				return "modules/wechat/front/wechatLogin";
				
			}
		}else{
			String message = "恭喜您，已消费"+score+"积分成功兑换了【"+proName+"】.";
			model.addAttribute("wechatId", wechatId);
			model.addAttribute("uid", uid);
			
			Integer myscore = member.getScore();
			
			if(Integer.parseInt(score )>myscore){
				message = "兑换失败,您目前的积分为"+myscore+"分,不能兑换积分为"+score+"的【"+proName +"】.";
			}else{
				//写兑换记录
				ExchangeRecord recorder = new ExchangeRecord();
				recorder.setCostScore(Integer.parseInt(score));
				
				ScoreExchange exchange = new ScoreExchange();
				exchange.setId(Long.parseLong(exchangeId));
				recorder.setExchange(exchange);
				recorder.setMember(member);
				recorder.setName(proName);
				recorder.setUser(user);
				recorder.setValid(false);
				recorder.setUpdateTime(new Date());
				recorder.setStatus(ExchangeRecord.STATUS_CLEAR );
				recorder.setRemarks(message);
				
				//保存兑换记录
				exchangeRecordService.save(recorder);
				model.addAttribute("recorder", recorder);
				//积分消费记录
				ScoreUtils.addScore(member, -Integer.parseInt(score ), "兑换【"+proName+"】消费积分");
				member.setScore(myscore-Integer.parseInt(score ));
			}
			model.addAttribute("message", message);
			
			
			return "modules/wechat/front/exchange/exchangeScoreOk";	
		}
		
		return "modules/wechat/front/exchange/exchangeScore";	
		
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-29  上午10:27:14
	 * @function <p> 微信会员绑定  </p>
	 * @param id
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "bind/{id}")
	public String bind(@PathVariable("id") Long id,Model model, HttpServletRequest request, HttpServletResponse response ) {
//		}
		
		User user = new User();
		user.setId(id);
		String message = "";
		
		String topage = request.getParameter("topage");
		String wechatId = request.getParameter("wechatId");
		String mobile = request.getParameter("mobile");
		
		
		WechatMember  wechatMember   =  wechatMemberService.getByWechatMemberId(user, wechatId);
		
		if(wechatMember != null ){		//已经绑定过的会员
			//"http://www.hdzhx.com/zxims/f/wechat/login/"+user.getId() +"?wechatId="+openId
			message = "尊敬的会员 "+wechatMember.getName()+" 您好,您早已成为我们的微会员,<br>您现在可以参与:<br>签到送积分<br>积分兑换<br>在线秒杀<br>在线抽奖";
			model.addAttribute("message", message);
			model.addAttribute("uid", id);
			model.addAttribute("id", id);
			model.addAttribute("wechatId", wechatId);
			model.addAttribute("wechatMember", wechatMember);
			return  "modules/wechat/front/wechatMember";
		}else{
			
		}
		
		model.addAttribute("topage", topage);
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		
		
		if("reg".equals(request.getParameter("action"))){	//保存绑定
			String name = request.getParameter("name");
			
			String password = request.getParameter("password");
			String birthday = request.getParameter("birthday");
			String sex = request.getParameter("sex");
			//WechatMember	member = addWechatMember(user, wechatId);
			//WechatMember wechatMember = wechatMemberService.getByWechatMemberId(user, wechatId);
			//WechatMember wechatMember = wechatMemberService.getByMobile(user, mobile);
			
			WechatMember  mobileMember  = wechatMemberService.getByMobile(user, mobile);
			
			if(wechatMember == null &&  mobileMember == null){		//绑定成功
				wechatMember  = new WechatMember()  ;
				wechatMember.setUser(user);
				wechatMember.setWechatId(wechatId);
				wechatMember.setScore(0);
				wechatMember.setName(name);
				wechatMember.setBirthday(birthday);
				wechatMember.setSex(sex);
				wechatMember.setMobile(mobile);
				wechatMember.setPassword(systemService.entryptMD5Pssword(password));
				wechatMember.setLastSignTime(null);
				wechatMemberService.save(wechatMember);
				//member = addWechatMember(user, wpuser);
				//ScoreUtils.addWechatMemberSignScore(wechatMember,1);
				message = "亲，恭喜您成为我们的微会员！<br>您现在可以参与:<br>签到送积分<br>积分兑换<br>在线秒杀<br>在线抽奖";
				
				/////
				//是 否注册会员有礼
				UserDefine userDefine = WechatUtils.getUserDefineByUserId(user.getId());
				
				if("1".equals(userDefine.getRegLottery())){	//注册会员有奖
					//TODO 生成注册奖品
					LotteryRecord lotteryRecord = new LotteryRecord();
					lotteryRecord.setSourceType(LotteryRecord.SURCE_TYPE_REG);
					lotteryRecord.setName(userDefine.getLotteryName());
					lotteryRecord.setStartTime(new Date());
					
					lotteryRecord.setEndTime(	com.boxin.framework.base.utils.DateUtils.getDelayDate(userDefine.getLotteryValidDays()));
					lotteryRecord.setMember(wechatMember);
					lotteryRecord.setStatus(LotteryRecord.STATUS_NORMAL);
					lotteryRecord.setUser(user);
					
					lotteryRecordService.save(lotteryRecord);
					model.addAttribute("regLottery", "恭喜您获得了本次注册会员送礼活动的【"+userDefine.getLotteryName()+"】,请返回微信点击【我的礼品】菜单获取电子凭证,并到附近实体店兑换礼品!");
				}
				
				model.addAttribute("message", message);
				model.addAttribute("info", "您现在可以参与:<p>签到送积分</p><p>积分兑换</p><p>在线秒杀</p>在线抽奖<p>...</p>");
				model.addAttribute("userName", name);
				return "modules/wechat/front/reg";
			}else{
				
				if(wechatMember != null && wechatMember.getMobile().equals(mobile)){
					message = "亲,您早已是我们的会员了,<br>您现在可以参与:<br>签到送积分<br>积分兑换<br>在线秒杀<br>在线抽奖";
				}else{
					message = "您输入的手机号["+mobile+"]已经与其它微信绑定，请确定是否输入错误!";
				}
				
				if(mobileMember != null){
					message = "您输入的手机号["+mobile+"]已经与其它微信绑定，请确定是否输入错误!";
				}
				
//				
				model.addAttribute("message", message);
				return "modules/wechat/front/reg";
			}
			
			
		}else{	//导航到指定页
			
			model.addAttribute("reg", "reg");
			model.addAttribute("id", id);
		}
		
		model.addAttribute("message", message);
		
		return "modules/wechat/front/reg";
	}
	
	
	
	
	
	
	
	public static String getTopage(String key){
		
		if(topageMap.isEmpty() || topageMap.size() ==0 ){
			topageMap.put("seckill", "redirect:" + Global.FRONT_PATH+ "/wechat/product/seckills");
			topageMap.put("reg", "modules/wechat/front/reg");
			topageMap.put("exchangeScore", "redirect:" + Global.FRONT_PATH + "/wechat/toexchange");
			topageMap.put("guestbook", "redirect:" + Global.FRONT_PATH + "/wechat/toguestbook");
			topageMap.put("toSignup", "redirect:" + Global.FRONT_PATH + "/wechat/toSignup");
		}
		
		return topageMap.get(key);
		
	}


}
